﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Collections.Concurrent;

namespace Se.Framework.Web.Mvc.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public abstract class InitializerAttribute : ActionFilterAttribute
    {
        private static readonly ConcurrentDictionary<string, InitializerAttribute> concurrent = new ConcurrentDictionary<string, InitializerAttribute>();

        private static readonly object initializerLock = new object();

        private readonly string key;

        public InitializerAttribute(string key)
        {
            this.key = key;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!concurrent.ContainsKey(key))
            {
                lock (initializerLock)
                {
                    if (!concurrent.ContainsKey(key))
                    {
                        this.Initialize();
                        concurrent.AddOrUpdate(key, this, Function);
                    }
                }
            }
        }

        private InitializerAttribute Function(string key, InitializerAttribute value)
        {
            return value;
        }

        protected abstract void Initialize();
    }
}
